package com.fzrskj.cloud.free.thridparty.pay.wechat;

import com.fzrskj.cloud.free.core.enums.DicParamEnum;
import com.fzrskj.cloud.free.core.enums.PayTypeEnum;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.DoubleUtil;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.user.bean.UserCharge;
import com.fzrskj.cloud.free.user.utils.FuncHandleUtils;
import com.fzrskj.cloud.free.user.utils.UserChargeUtils;
import com.fzrskj.cloud.free.user.utils.UserLogUtils;
import com.winiis.component.pay.wechat.service.WechatPaySuccess;
import com.winiis.component.utils.client.RestClientUtils;
import ms.core.db.ConnectionContext;
import ms.core.tool.StrTool;
import net.sf.json.JSONObject;

import java.util.Map;

/**
 * WechatPaySuccssImpl.
 *
 * @author zj.
 *         Created on 2018/12/28 0028.
 */
public class WechatPaySuccessImpl implements WechatPaySuccess {
    boolean canContinueDealOrder = true;
    Integer agentId = 0;
    String bizOrderId = "";

    /**
     * 微信支付实现.
     * @param callbackParam 用户支付成功微信回设通知参数。
     *                  详细参考：https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_7&index=8
     * @param orderInfo 支付订单信息，邮微信提供。为空表示订单查询失败或签名校验失败。
     */
    @Override
    public void successCall(Map<String, String> callbackParam, Map<String, String> orderInfo) {
        try {
            if (null != orderInfo) {
                String orderId = orderInfo.get("out_trade_no");
                UserChargeUtils userChargeUtils = new UserChargeUtils();
                UserCharge charge = userChargeUtils.getUserCharge(orderId);
                if (null == charge) {
                    UserLogUtils.addLog(this, 1000, "微信支付失败，未打到订单：" + orderId);
                    return;
                }

                String randStats = CStrTool.randStr(2);
                if (!"N".equals(charge.getStatus())) {
                    UserLogUtils.addLog(this, 1000, "微信支付失败，订单状态不正确：" + charge.toString());
                    return;
                }
                charge.setStatus(randStats);
                userChargeUtils.uptUsercharge(charge);

                Integer amount = DoubleUtil.mul(charge.getAmount(), Double.valueOf(100)).intValue();
                Integer totalFee = Integer.valueOf(orderInfo.get("total_fee"));
                if (!totalFee.equals(amount)) {
                    UserLogUtils.addLog(this, 1000, "微信支付失败，订单金额不相等：" + charge.toString());
                    return;
                }
                String billNo = orderInfo.get("transaction_id");

                //获取用户代理，设置上下文代理信息
                CloudContextUtils.setAgentId(charge.getAgentId());

                //系统入账
                FuncHandleUtils funcHandle = new FuncHandleUtils();
                String remark = "微信在线支付，支付订单号【" + orderId + "】";
                //费率计算
                String rateStr = DicParamUtils.getParamValue(DicParamEnum.WECHAT_RATE.getVal());
                if (StrTool.isBlankStr(rateStr)) {
                    rateStr = "0";
                }
                Double rateDouble = Double.valueOf(rateStr);
                Double rate = DoubleUtil.sub(1.0, DoubleUtil.divide(rateDouble, 100.0));
                Double realAmount = DoubleUtil.mul(rate, charge.getAmount(), 2);
                Double rateAmount = DoubleUtil.sub(charge.getAmount(), realAmount, 2);
                remark += "；费率：" + String.valueOf(rateAmount);
                String result = funcHandle.FinanceAccount(charge.getUserName(), 100, remark, orderId, PayTypeEnum.WXPAY.getTag(), billNo, realAmount, charge.getUserName(), charge.getAgentId());
                UserLogUtils.addLog(this, 1000, "微信支付成功，系统自动入结果：【" + result + "】");

                //生成财务记录并更新充值记录状态
                JSONObject obj = JSONObject.fromObject(result);
                if ("0".equals(obj.getString("code").trim())) {

                    //如果是下级代理的会员入款，需要为中间所有的代理账户入款
                    if (!charge.getAgentId().equals(charge.getFromAgentUserId())) {
                        this.canContinueDealOrder = false;
                        this.agentId = charge.getAgentId();
                        funcHandle.refundsForAgent(charge.getAgentId(), charge.getFromAgentUserId(), orderId, PayTypeEnum.WXPAY.getTag(), billNo, realAmount, charge.getUserName(), remark);
                    }

                    charge.setStatus("Y");
                    userChargeUtils.uptUsercharge(charge);

                    //订单处理
                    if (!StrTool.isBlankStr(charge.getBizOrderId()) && this.canContinueDealOrder) {
                        FuncHandleUtils hand = new FuncHandleUtils();
                        String[] orders = charge.getBizOrderId().split(",");
                        for (int i = 0; i < orders.length; i++) {
                            hand.HandleOnLine(orders[i]);
                        }
                    }

                    //通知订单发起代理，触发充值关联订单处理操作
                    if (!StrTool.isBlankStr(charge.getBizOrderId()) && !this.canContinueDealOrder) {
                        String webUrl = DicParamUtils.getParamValueByAgentIdAndParamName("weburl", this.agentId);
                        webUrl += (webUrl.endsWith("/") ? "" : "/") + "pay_success?type=alipay&orderId=" + charge.getBizOrderId();
                        RestClientUtils clientUtils = new RestClientUtils();
                        String noticeResponse = clientUtils.get(webUrl);
                        UserLogUtils.addLog(this, CloudContextUtils.getAdminId(), "通知代理充值结果，请求地址：[" +
                                webUrl + "]，映应结果：[" + noticeResponse + "]");
                    }

                    UserLogUtils.addLog(this, charge.getUserId(), "微信支付成功，系统自动入账成功");
                } else {
                    UserLogUtils.addLog(this, charge.getUserId(), "微信支付成功，系统自动入账失败！");
                }
            }
        } finally {
            ConnectionContext.closeAllConnection();
        }
    }
}
